package com.doit.doit26;

import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class TransactionDemo {

  public static void main(String[] args) throws ClassNotFoundException, SQLException {
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = DriverManager
        .getConnection("jdbc:mysql://localhost:3306/lvxiaolong", "root", "123456");
    //停止sql的自动提交功能
    //#######################################开启事务##############################################
    conn.setAutoCommit(false);
    BigDecimal money = new BigDecimal(1000);
    //sql1
    PreparedStatement ps1 = conn
        .prepareStatement("update t_account set money=money-? where id=?");
    ps1.setBigDecimal(1, money);
    ps1.setInt(2, 1);
    ps1.executeUpdate();

    //有异常
    System.out.println(1/0);

    //sql2
    PreparedStatement ps2 = conn
        .prepareStatement("update t_account set money=money+? where id=?");
    ps2.setBigDecimal(1, money);
    ps2.setInt(2, 2);
    ps2.executeUpdate();
    //手动提交
    conn.commit();
    //#######################################提交事务##############################################
    ps2.close();
    ps1.close();
    conn.close();
  }
}
